declare @qry nvarchar(max)
		,@Nindice nvarchar(max)
		,@Frac	  float
		,@Ntabla varchar(max)

declare qmantenimiento cursor for
			select  b.name, avg_fragmentation_in_percent,o.name as 'nt'
					from sys.dm_db_index_physical_stats(DB_ID('AdventureWorks2012'),NULL,NULL,NULL,'DETAILED') as a
						JOIN sys.indexes AS b ON a.object_id = b.object_id AND a.index_id = b.index_id
						join sys.tables as o on b.object_id=o.object_id

open qmantenimiento 
fetch next from qtablas INTO @Nindice,@Frac,@Ntabla
while @@FETCH_STATUS=0
begin
	if(@Frac < 30)
	begin
	set @qry=N'ALTER INDEX '+@Nindice+' on '+@Ntabla+' reorganize '
	print @qury
	end
	else
	begin
	set @qry=N'ALTER INDEX '+@Nindice+' on '+@Ntabla+' rebuild '
	print @qury
	end
end